package com.zhl.gradledemo.producer;

import com.zhl.gradledemo.model.Order;
import com.zhl.gradledemo.service.BrokerMessageLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 消息发送,生产
 */
@Component
public class OrderSender {

    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private BrokerMessageLogService brokerMessageLogService;

    //消息发送的回调函数: confirm确认
    final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            System.out.println("correlationData: " + correlationData);
            String messageId = correlationData.getId();
            if (ack) {
                //如果confirm返回成功 则进行更新
                brokerMessageLogService.changeBrokerMessageLogStatus(messageId, "1");
            } else {
                //失败则进行具体的后续操作:重试 或者补偿等手段
                System.err.println("异常处理...");
            }
        }
    };

    //消息发送
    public void send(Order order) {

        rabbitTemplate.setConfirmCallback(confirmCallback);

        CorrelationData correlationData = new CorrelationData(order.getMessageId());//消息的id

        rabbitTemplate.convertAndSend("order-exchange",//exchange
                "order.abcd",//routingKey
                order,//消息内容
                correlationData);//消息唯一id
    }


}
